#include "hal.h"
#include <raw_api.h>

#if (HAL_USE_UART > 0) 

HAL_ERROR uart_init(UART_DRIVER *uart) 
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT(uart != 0);

	mutex_error = raw_mutex_get(&uart->uart_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	ret = uart_lld_init(uart);

	mutex_error = raw_mutex_put(&uart->uart_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);

	return ret;
	
}

HAL_ERROR uart_start(UART_DRIVER *uart, UART_CONFIG *config) 
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT((uart != 0) && (config != 0));

	mutex_error = raw_mutex_get(&uart->uart_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	uart->config = config;
	ret = uart_lld_start(uart, config);
	
	mutex_error = raw_mutex_put(&uart->uart_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	return ret;
}


HAL_ERROR uart_stop(UART_DRIVER *uart) 
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT(uart != 0);

	mutex_error = raw_mutex_get(&uart->uart_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	ret = uart_lld_stop(uart);
	
	mutex_error = raw_mutex_put(&uart->uart_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	return ret;
}


HAL_ERROR uart_transmit(UART_DRIVER *uart, RAW_U8 *tx_buf, RAW_U32 tx_bytes, RAW_U32 timeout)
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT(uart != 0);

	mutex_error = raw_mutex_get(&uart->uart_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	ret = uart_lld_transmit(uart, tx_buf, tx_bytes, timeout);
	
	mutex_error = raw_mutex_put(&uart->uart_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	return ret;

}

HAL_ERROR uart_receive(UART_DRIVER *uart, RAW_U8 *rx_buf, RAW_U32 rx_bytes, RAW_U32 timeout)
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT(uart != 0);

	mutex_error = raw_mutex_get(&uart->uart_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	ret = uart_lld_receive(uart, rx_buf, rx_bytes, timeout);
	
	mutex_error = raw_mutex_put(&uart->uart_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	return ret;

}


HAL_ERROR uart_deinit(UART_DRIVER *uart) 
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;

	RAW_ASSERT(uart != 0);
	
	mutex_error = raw_mutex_get(&uart->uart_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	ret = uart_lld_deinit(uart);

	mutex_error = raw_mutex_put(&uart->uart_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	return ret;
	
}



#endif

